package com.yan.service;

import com.yan.bo.EmailSender;
import com.yan.bo.RequestInfo;
import com.yan.bo.RequestStat;
import com.yan.storage.MetricsStorage;

import java.util.*;

/**
 * @author yanheng
 * @data 2020/1/16 18:51
 */
public class EmailReporter {
    private static final Long DAY_HOURS_IN_SECONDS = 86400L;

    private MetricsStorage metricsStorage;
    private EmailSender emailSender;
    private List<String> toAddress = new ArrayList<>();

    public EmailReporter(MetricsStorage storage){
        this(storage, new EmailSender());
    }

    public EmailReporter(MetricsStorage storage, EmailSender sender){
        this.metricsStorage = storage;
        this.emailSender = sender;
    }

    public void addToAddress(String address){
        toAddress.add(address);
    }

    public void startDailyReport(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        calendar.add(Calendar.HOUR_OF_DAY, 0);
        calendar.add(Calendar.MINUTE, 0);
        calendar.add(Calendar.SECOND, 0);
        calendar.add(Calendar.MILLISECOND, 0);
        Date firstTime = new Date();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                long durationInMillis = DAY_HOURS_IN_SECONDS * 1000;
                long endTimeInMillis = System.currentTimeMillis();
                long startTimeInMillis = endTimeInMillis - durationInMillis;
                Map<String, List<RequestInfo>> requestInfos = metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMillis);
                Map<String, RequestStat> stats = new HashMap<>();
                for (Map.Entry<String, List<RequestInfo>> entry: requestInfos.entrySet()) {
                    String apiName = entry.getKey();
                    List<RequestInfo> requestInfosPerApi = entry.getValue();
                    RequestStat requestStat = Aggregator.aggregate(requestInfosPerApi, durationInMillis);
                    stats.put(apiName, requestStat);
                }
            }
        }, firstTime, DAY_HOURS_IN_SECONDS);
    }
}
